package com.yami.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.RestTemplateUtil;
import com.yami.shop.service.WechatService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * WechatServiceImpl
 *
 * @Author Administrator
 * @Date 2025/4/14 13:02
 */
@Service
@Slf4j
public class WechatServiceImpl implements WechatService {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Override
    public String wxLogin(String jsCode) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
            Map<String,String> map = new HashMap<>();
            String res = restTemplateUtil.getData(url,map);
            JSONObject sendIntensifyOb = JSONObject.parseObject(res);


            String openId = sendIntensifyOb.getString("openid");
            if(StrUtil.isNotBlank(openId)){
                return openId;
            }else {
                throw new YamiShopBindException("微信授权失败");
            }
        }catch (Exception e){
            log.error("微信授权失败,{}",e.getMessage());
            throw new YamiShopBindException("微信授权失败");
        }
    }
}
